| Conditions | 10 |
| Total Lines | 48 |
| Code Lines | 41 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Complex classes like rewrite.ts ➔ rewrite often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import {createReadStream} from 'fs' |
||
| 13 | |||
| 14 | async function rewrite(filename: string, lines: string[], eol: string, checkMode: boolean) { |
||
| 15 | const {length} = lines |
||
| 16 | , fileExists = await $exists(filename) |
||
| 17 | |||
| 18 | if (fileExists) { |
||
| 19 | const lineReader = createInterface({ |
||
| 20 | input: createReadStream(filename), |
||
| 21 | crlfDelay: Infinity, |
||
| 22 | historySize: 0 |
||
| 23 | }) |
||
| 24 | |||
| 25 | let isSame = true |
||
| 26 | , row = 0 |
||
| 27 | |||
| 28 | for await (const line of lineReader) { |
||
| 29 | if (line !== lines[row]) { |
||
| 30 | isSame = false |
||
| 31 | break |
||
| 32 | } |
||
| 33 | row++ |
||
| 34 | } |
||
| 35 | |||
| 36 | lineReader.close() |
||
| 37 | |||
| 38 | if (isSame) { |
||
| 39 | if (lines[row] === "") |
||
| 40 | row++ |
||
| 41 | if (length === row) |
||
| 42 | return |
||
| 43 | } |
||
| 44 | } |
||
| 45 | |||
| 46 | if (checkMode) |
||
| 47 | throw new Error(`Content of "${filename}" should be another`) |
||
| 48 | |||
| 49 | const tempFile = await tempFileName() |
||
| 50 | , fd = await $open(tempFile, "w") |
||
| 51 | |||
| 52 | for (let i = 0; i < length; i++) |
||
| 53 | await $write(fd, `${ |
||
| 54 | i ? eol : '' |
||
| 55 | }${ |
||
| 56 | lines[i] |
||
| 57 | }`) |
||
| 58 | |||
| 59 | await $close(fd) |
||
| 60 | await $rename(tempFile, filename) |
||
| 61 | } |
||
| 62 |